import 'dart:async';
import 'dart:convert';
import 'dart:math';

import 'package:e_reception_flutter/media_library/media_library_index/bean/media_detail_response_bean.dart';
import 'package:e_reception_flutter/media_library/media_library_index/bean/media_urgent_response_bean.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/media_library_index_refresh_even.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/media_urgent_update.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/terminal_num_update_event.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/update_terminal_play_list_status_event.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/location_repository/location_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/index/bean/index_bind_termainal_info.dart';
import 'package:e_reception_flutter/ui/index/bean/index_top_base_info.dart';
import 'package:e_reception_flutter/ui/index/bean/index_top_punch_info.dart';
import 'package:e_reception_flutter/ui/index_nav/even/index_refresh_even.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail/bean/terminal_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail/widgets/operation_success_tips_dialog.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/vg_date_time_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_location_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';

import 'bean/index_top_info_response_bean.dart';
import 'bean/update_terminal_play_list_status_bean.dart';

class IndexViewModel extends BaseViewModel{

  // ValueNotifier<IndexTopInfoDataBean> topInfoValueNotifier;
  ValueNotifier<IndexTopBaseInfo> indexTopBaseValueNotifier;
  ValueNotifier<PVCntBean> indexTopPunchInfoValueNotifier;
  ValueNotifier<IndexBindTermainalInfo> bindTermainalInfoValueNotifier;
  // ValueNotifier<IndexBindTermainalInfo> punchAndTerminalInfoValueNotifier;
  ValueNotifier<TerminalDetailResponseBean> detailValueNotifier;
  ValueNotifier<MediaUrgentResponseBean> urgentValueNotifier;
  StreamSubscription homePageInterfaceEventMonitor;
  ///app终端管理页面
  // static const String INDEX_TOP_INFO_API =ServerApi.BASE_URL + "app/appTerminalManageHome";

  static const String CURRENT_TERMINAL_LIST_SIZE = "current_terminal_list_size";

  static const String TOP_INFO_CACHE_DATA_KEY = "top_info_cache_data_key";

  ///查询紧急通告模式
  static const String GET_URGENT_API = ServerApi.BASE_URL + "app/appGetUrgent";
  ///重复/暂停重复播放
  static const String REPEAT_PLAY_API = ServerApi.BASE_URL + "app/appStopPicByhsn";
  ///根据终端取消重复播放
  static const String CANCEL_REPEAT_PLAY_BY_HSN_API = ServerApi.BASE_URL + "app/appCancelStopPicByhsn";
  ///app终端开关音量  00开 01关
  static const String CHANGE_VOLUME_API =
     ServerApi.BASE_URL + "app/appSoundSwitch";

  IndexViewModel(BaseState<StatefulWidget> state) : super(state){
    // topInfoValueNotifier = ValueNotifier(null);
    indexTopPunchInfoValueNotifier = ValueNotifier(null);
    indexTopBaseValueNotifier = ValueNotifier(null);
    bindTermainalInfoValueNotifier = ValueNotifier(null);
    // punchAndTerminalInfoValueNotifier = ValueNotifier(null);
    detailValueNotifier = ValueNotifier(null);
    urgentValueNotifier = ValueNotifier(null);
  }

  @override
  void onDisposed() {
    indexTopPunchInfoValueNotifier?.dispose();
    indexTopBaseValueNotifier?.dispose();
    bindTermainalInfoValueNotifier?.dispose();
    // punchAndTerminalInfoValueNotifier?.dispose();
    // topInfoValueNotifier?.dispose();
    detailValueNotifier?.dispose();
    urgentValueNotifier?.dispose();
    homePageInterfaceEventMonitor?.cancel();
    super.onDisposed();
  }
  bool showLoad = false;

  //合并获取公司基础信息与打卡信息
  //1.appHomeBaseInfo
  void getHomeCompanyBaseInfoAndPunchInfo({bool hideShowLoad, String authId}){
    print("appHomeBaseInfo========= getHomeCompanyBaseInfoAndPunchInfo");
    if(StringUtils.isEmpty(UserRepository.getInstance().authId)){
      VgEventBus.global.send(new HomePageInterfaceEventMonitor(showLoad: false));
      showLoad = false;
      print("authId为空忽略请求");
      return;
    }
    if(hideShowLoad != null){
      showLoad = hideShowLoad;
    }
    homePageInterfaceEventMonitor = VgEventBus.global.on<UpdateHomePageEventMonitor>().listen((event) {
      showLoad = true;
    });
    if(!showLoad){
      VgEventBus.global.send(new HomePageInterfaceEventMonitor(showLoad: true));
      showLoad = true;
    }
    String currentDate = DateUtil.getDateStrByDateTime(DateTime.now(), format: DateFormat.YEAR_MONTH_DAY);
    String cacheKey = UserRepository.getInstance().getHomeCompanyBaseInfoAndPunchInfoCacheKey();
    ///获取缓存数据
    Future<String> future = SharePreferenceUtil.getString(cacheKey);
    Future<String> topInfoCacheData = SharePreferenceUtil.getString(TOP_INFO_CACHE_DATA_KEY);
    future.then((jsonStr){
      if(!StringUtils.isEmpty(jsonStr)){
        print("缓存key：" + cacheKey + "有缓存");
        Map map = json.decode(jsonStr);
        IndexTopBaseInfo bean = IndexTopBaseInfo.fromMap(map);
        if(bean != null){
          if(!isStateDisposed){
            //打卡数据相关
            topInfoCacheData.then((cacheDate) {
              if(!StringUtils.isEmpty(cacheDate) && currentDate != cacheDate){
                bean?.data?.PVCnt?.historyPunchCnt = 0;
                bean?.data?.PVCnt?.punchcnt = 0;
                bean?.data?.PVCnt?.visitorcnt = 0;
              }
              if(!isStateDisposed){
                print("缓存key：" + cacheKey + "使用了缓存");
                indexTopPunchInfoValueNotifier?.value = bean?.data?.PVCnt;
              }else{
                print("缓存key：" + cacheKey + "未使用缓存0");
              }
            });
            //基础信息相关
            print("缓存key：" + cacheKey + "使用了缓存");
            indexTopBaseValueNotifier?.value = bean;
          }else{
            print("缓存key：" + cacheKey + "未使用缓存0");
          }
        }else{
          print("缓存key：" + cacheKey + "未使用缓存1");
        }
      }else{
        if(!isStateDisposed){
          indexTopPunchInfoValueNotifier?.value = new PVCntBean();
          print("卡片：3333333");
          indexTopBaseValueNotifier?.value = new IndexTopBaseInfo();
        }
      }
    });

    String requestAuthId = StringUtils.isNotEmpty(authId)?authId:(UserRepository.getInstance().authId ?? "");
    VgHttpUtils.get(NetApi.HOME_COMPANY_BASE_INFO,params: {
      "authId":requestAuthId,
      "timeStamp":VgDateTimeUtils.getCurrentTimeStamp(),
    },callback: BaseCallback(
        onSuccess: (val){
          String currentAuthId = UserRepository.getInstance().authId;
          if(requestAuthId != currentAuthId){
            print("两次authId不一致，忽略此次请求");
            return;
          }
          IndexTopBaseInfo bean = IndexTopBaseInfo.fromMap(val);
          if(!isStateDisposed){
            print("getHomeCompanyBaseInfoAndPunchInfo 更新企业信息0");
            indexTopBaseValueNotifier?.value = bean;
            indexTopPunchInfoValueNotifier?.value = bean.data.PVCnt;
          }
          //处理打卡布局后续逻辑
          VgEventBus.global.send(new HomePageInterfaceEventMonitor(showLoad: false));
          showLoad = false;
          //缓存获取打卡数据的日期，便于日期切换时将不是当前日期的缓存数据置为0
          SharePreferenceUtil.putString(TOP_INFO_CACHE_DATA_KEY, currentDate);
          //缓存数据
          SharePreferenceUtil.putString(cacheKey, json.encode(bean));
        },
        onError: (msg){
          VgEventBus.global.send(new HomePageInterfaceEventMonitor(showLoad: false));
          showLoad = false;
          VgToastUtils.toast(AppMain.context, msg);
          getHomeCompanyBaseInfoAndPunchInfoFromNet(hideShowLoad: hideShowLoad, authId: authId, from: "getHomeCompanyBaseInfoAndPunchInfo onError");
        }
    ));
  }

  void getHomeCompanyBaseInfoAndPunchInfoFromNet({String authId, String currentDate, String cacheKey, bool hideShowLoad, String from}){
    print("appHomeBaseInfo========= getHomeCompanyBaseInfoAndPunchInfoFromNet:" + from);
    print("首页打卡信息从网络获取更新");
    if(StringUtils.isEmpty(UserRepository.getInstance().authId)){
      VgEventBus.global.send(new HomePageInterfaceEventMonitor(showLoad: false));
      showLoad = false;
      print("authId为空忽略请求");
      return;
    }
    if(hideShowLoad != null){
      showLoad = hideShowLoad;
    }
    homePageInterfaceEventMonitor = VgEventBus.global.on<UpdateHomePageEventMonitor>().listen((event) {
      showLoad = true;
    });
    if(!showLoad){
      VgEventBus.global.send(new HomePageInterfaceEventMonitor(showLoad: true));
      showLoad = true;
    }
    String requestAuthId = StringUtils.isNotEmpty(authId)?authId:(UserRepository.getInstance().authId ?? "");
    VgHttpUtils.get(NetApi.HOME_COMPANY_BASE_INFO,params: {
      "authId":requestAuthId,
      "timeStamp":VgDateTimeUtils.getCurrentTimeStamp(),
    },callback: BaseCallback(
        onSuccess: (val){
          String currentAuthId = UserRepository.getInstance().authId;
          if(requestAuthId != currentAuthId){
            print("两次authId不一致，忽略此次请求");
            return;
          }
          IndexTopBaseInfo bean = IndexTopBaseInfo.fromMap(val);
          if(!isStateDisposed){
            print("getHomeCompanyBaseInfoAndPunchInfo 更新企业信息1");
            indexTopBaseValueNotifier?.value = bean;
            indexTopPunchInfoValueNotifier?.value = bean.data.PVCnt;
          }
          //处理打卡布局后续逻辑
          VgEventBus.global.send(new HomePageInterfaceEventMonitor(showLoad: false));
          showLoad = false;
          //缓存获取打卡数据的日期，便于日期切换时将不是当前日期的缓存数据置为0
          if(StringUtils.isEmpty(currentDate)){
            currentDate = DateUtil.getDateStrByDateTime(DateTime.now(), format: DateFormat.YEAR_MONTH_DAY);
          }
          SharePreferenceUtil.putString(TOP_INFO_CACHE_DATA_KEY, currentDate);
          //缓存数据
          if(StringUtils.isEmpty(cacheKey)){
            cacheKey = UserRepository.getInstance().getHomeCompanyBaseInfoAndPunchInfoCacheKey();
          }
          SharePreferenceUtil.putString(cacheKey, json.encode(bean));
        },
        onError: (msg){
          VgEventBus.global.send(new HomePageInterfaceEventMonitor(showLoad: false));
          showLoad = false;
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  //仅获取终端信息
  //2.appHomeInfo
  void getHomeTerminalInfo(int index,{String unbindHsn,String gps, String authId}){
    if(StringUtils.isEmpty(UserRepository.getInstance().authId)){
      print("authId为空忽略请求");
      return;
    }
    String cacheKey = UserRepository.getInstance().getHomeTerminalInfoCacheKey();
    ///获取缓存数据
    Future<String> future = SharePreferenceUtil.getString(cacheKey);
    future.then((jsonStr){
      if(!StringUtils.isEmpty(jsonStr)){
        print("缓存key：" + cacheKey + "有缓存");
        Map map = json.decode(jsonStr);
        IndexBindTermainalInfo bean = IndexBindTermainalInfo.fromMap(map);
        if(bean != null){
          if(!isStateDisposed){
            //终端列表相关
            print("缓存key：" + cacheKey + "使用了缓存");
            bindTermainalInfoValueNotifier?.value = bean;
          }else{
            print("缓存key：" + cacheKey + "未使用缓存1");
          }
          //获取某个终端详情
          ///刷新后更新当前角色
          if(bean?.data != null
              && bean?.data?.bindTerminalList != null
              && bean.data.bindTerminalList.length>index){
            if(StringUtils.isEmpty(unbindHsn) || (unbindHsn != bean?.data?.bindTerminalList[index]?.hsn)){
              getTerminalDetail(bean?.data?.bindTerminalList[index]?.hsn);
            }
          }
        }else{
          print("缓存key：" + cacheKey + "未使用缓存2");
        }
      }else{
        if(!isStateDisposed){
          bindTermainalInfoValueNotifier?.value = new IndexBindTermainalInfo();
        }
      }
    });
    String requestAuthId = StringUtils.isNotEmpty(authId)?authId:(UserRepository.getInstance().authId ?? "");
    if(StringUtils.isNotEmpty(gps)){
      VgHttpUtils.get(NetApi.HOME_PUNCH_AND_TERMINAL_INFO,params: {
        "authId":requestAuthId,
        "gps": gps,
      },callback: BaseCallback(
          onSuccess: (val){
            String currentAuthId = UserRepository.getInstance().authId;
            if(requestAuthId != currentAuthId){
              print("两次authId不一致，忽略此次请求");
              return;
            }
            IndexBindTermainalInfo bean = IndexBindTermainalInfo.fromMap(val);
            if(!isStateDisposed){
              bindTermainalInfoValueNotifier?.value = bean;
            }
            //处理终端布局后续逻辑
            SharePreferenceUtil.putString(cacheKey, json.encode(bean));
            if(bean != null && bean.data != null && bean.data.bindTerminalList != null){
              VgEventBus.global.send(new TerminalNumRefreshEvent(bean.data.bindTerminalList.length));
            }
            if(bindTermainalInfoValueNotifier?.value != null
                && bindTermainalInfoValueNotifier?.value?.data?.bindTerminalList != null
                && bindTermainalInfoValueNotifier.value.data.bindTerminalList.length>index){
              getTerminalDetail(bindTermainalInfoValueNotifier?.value?.data?.bindTerminalList[index]?.hsn);
            }
          },
          onError: (msg){
            showLoad = false;
            VgToastUtils.toast(AppMain.context, msg);
          }
      ));
    }else{
      Future<String> latlng = VgLocationUtils.getCacheLatLngString();
      latlng.then((value){
        ///网络请求
        VgHttpUtils.get(NetApi.HOME_PUNCH_AND_TERMINAL_INFO,params: {
          "authId":requestAuthId,
          "gps": value,
        },callback: BaseCallback(
            onSuccess: (val){
              String currentAuthId = UserRepository.getInstance().authId;
              if(requestAuthId != currentAuthId){
                print("两次authId不一致，忽略此次请求");
                return;
              }
              IndexBindTermainalInfo bean = IndexBindTermainalInfo.fromMap(val);
              if(!isStateDisposed){
                bindTermainalInfoValueNotifier?.value = bean;
              }
              //处理终端布局后续逻辑
              SharePreferenceUtil.putString(cacheKey, json.encode(bean));
              if(bean != null && bean.data != null && bean.data.bindTerminalList != null){
                VgEventBus.global.send(new TerminalNumRefreshEvent(bean.data.bindTerminalList.length));
              }
              VgEventBus.global.send(new HomePageInterfaceEventMonitor(showLoad: false));
              showLoad = false;
              if(bindTermainalInfoValueNotifier?.value != null
                  && bindTermainalInfoValueNotifier?.value?.data?.bindTerminalList != null
                  && bindTermainalInfoValueNotifier.value.data.bindTerminalList.length>index){
                getTerminalDetail(bindTermainalInfoValueNotifier?.value?.data?.bindTerminalList[index]?.hsn);
              }
            },
            onError: (msg){
              showLoad = false;
              VgToastUtils.toast(AppMain.context, msg);
            }
        ));
      });
    }
  }


  //重写getTopInfoHttp接口
  //1.appHomeBaseInfo公司基础信息接口
  void getHomeBaseInfo({String authId}){
    print("appHomeBaseInfo========= getHomeBaseInfo");
    if(StringUtils.isEmpty(UserRepository.getInstance().authId)){
      print("authId为空忽略请求");
      return;
    }
    // String currentDate = DateUtil.getDateStrByDateTime(DateTime.now(), format: DateFormat.YEAR_MONTH_DAY);
    String cacheKey = UserRepository.getInstance().getHomeCompanyBaseInfoCacheKey();
    ///获取缓存数据
    Future<String> future = SharePreferenceUtil.getString(cacheKey);
    // Future<String> topInfoCacheData = SharePreferenceUtil.getString("app/appHomeBaseInfo");
    future.then((jsonStr){
      if(!StringUtils.isEmpty(jsonStr)){
        print("缓存key：" + cacheKey + "有缓存");
        Map map = json.decode(jsonStr);
        IndexTopBaseInfo bean = IndexTopBaseInfo.fromMap(map);
        if(bean != null){
          if(!isStateDisposed){
            print("缓存key：" + cacheKey + "使用了缓存");
            indexTopBaseValueNotifier?.value = bean;
          }else{
            print("缓存key：" + cacheKey + "未使用缓存0");
          }
        }else{
          print("缓存key：" + cacheKey + "未使用缓存1");
        }
      }else{
        if(!isStateDisposed){
          indexTopBaseValueNotifier?.value = new IndexTopBaseInfo();
        }
      }
    });
    String requestAuthId = StringUtils.isNotEmpty(authId)?authId:(UserRepository.getInstance().authId ?? "");
    VgHttpUtils.get(NetApi.HOME_COMPANY_BASE_INFO,params: {
      "authId":StringUtils.isNotEmpty(authId)?authId:(UserRepository.getInstance().authId ?? ""),
      "timeStamp":VgDateTimeUtils.getCurrentTimeStamp(),
      // "authId":UserRepository.getInstance().authId ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          String currentAuthId = UserRepository.getInstance().authId;
          if(requestAuthId != currentAuthId){
            print("两次authId不一致，忽略此次请求");
            return;
          }
          IndexTopBaseInfo bean = IndexTopBaseInfo.fromMap(val);
          if(!isStateDisposed){
            indexTopBaseValueNotifier?.value = bean;
          }
          //缓存数据
          SharePreferenceUtil.putString(cacheKey, json.encode(bean));
        },
        onError: (msg){
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }
  
  //2，3首页打卡信息以及终端信息
  void getPunchAndTerminalInfo(int index,{bool hideShowLoad, String unbindHsn,String gps, String authId}){
    if(StringUtils.isEmpty(UserRepository.getInstance().authId)){
      VgEventBus.global.send(new HomePageInterfaceEventMonitor(showLoad: false));
      showLoad = false;
      print("authId为空忽略请求");
      return;
    }
    if(hideShowLoad != null){
      showLoad = hideShowLoad;
    }
    homePageInterfaceEventMonitor = VgEventBus.global.on<UpdateHomePageEventMonitor>().listen((event) {
      showLoad = true;
    });
    if(!showLoad){
      VgEventBus.global.send(new HomePageInterfaceEventMonitor(showLoad: true));
      showLoad = true;
    }
    String currentDate = DateUtil.getDateStrByDateTime(DateTime.now(), format: DateFormat.YEAR_MONTH_DAY);
    String cacheKey = UserRepository.getInstance().getHomePunchAndTerminalInfoCacheKey();
    ///获取缓存数据
    Future<String> future = SharePreferenceUtil.getString(cacheKey);
    Future<String> topInfoCacheData = SharePreferenceUtil.getString(TOP_INFO_CACHE_DATA_KEY);
    future.then((jsonStr){
      if(!StringUtils.isEmpty(jsonStr)){
        print("缓存key：" + cacheKey + "有缓存");
        Map map = json.decode(jsonStr);
        IndexBindTermainalInfo bean = IndexBindTermainalInfo.fromMap(map);
        if(bean != null){
          if(!isStateDisposed){
            //打卡数据相关
            topInfoCacheData.then((cacheDate) {
              if(!StringUtils.isEmpty(cacheDate) && currentDate != cacheDate){
                bean?.data?.PVCnt?.historyPunchCnt = 0;
                bean?.data?.PVCnt?.punchcnt = 0;
                bean?.data?.PVCnt?.visitorcnt = 0;
              }
              if(!isStateDisposed){
                print("缓存key：" + cacheKey + "使用了缓存");
                indexTopPunchInfoValueNotifier?.value = bean?.data?.PVCnt;
              }else{
                print("缓存key：" + cacheKey + "未使用缓存0");
              }
            });
            //终端列表相关
            print("缓存key：" + cacheKey + "使用了缓存");
            bindTermainalInfoValueNotifier?.value = bean;


          }else{
            print("缓存key：" + cacheKey + "未使用缓存1");
          }
          //获取某个终端详情
          ///刷新后更新当前角色
          if(bean?.data != null
              && bean?.data?.bindTerminalList != null
              && bean.data.bindTerminalList.length>index){
            if(StringUtils.isEmpty(unbindHsn) || (unbindHsn != bean?.data?.bindTerminalList[index]?.hsn)){
              getTerminalDetail(bean?.data?.bindTerminalList[index]?.hsn);
            }
          }
        }else{
          print("缓存key：" + cacheKey + "未使用缓存2");
        }
      }else{
        if(!isStateDisposed){
          indexTopPunchInfoValueNotifier?.value = new PVCntBean();
          print("卡片：3333333");
          bindTermainalInfoValueNotifier?.value = new IndexBindTermainalInfo();
        }
      }
    });

    String requestAuthId = StringUtils.isNotEmpty(authId)?authId:(UserRepository.getInstance().authId ?? "");
    if(StringUtils.isNotEmpty(gps)){
      VgHttpUtils.get(NetApi.HOME_PUNCH_AND_TERMINAL_INFO,params: {
        "authId":requestAuthId,
        "gps": gps,
      },callback: BaseCallback(
          onSuccess: (val){
            String currentAuthId = UserRepository.getInstance().authId;
            if(requestAuthId != currentAuthId){
              print("两次authId不一致，忽略此次请求");
              return;
            }
            IndexBindTermainalInfo bean = IndexBindTermainalInfo.fromMap(val);
            if(!isStateDisposed){
              bindTermainalInfoValueNotifier?.value = bean;
              indexTopPunchInfoValueNotifier?.value = bean.data.PVCnt;
            }
            //处理打卡布局后续逻辑
            VgEventBus.global.send(new HomePageInterfaceEventMonitor(showLoad: false));
            showLoad = false;
            //缓存获取打卡数据的日期，便于日期切换时将不是当前日期的缓存数据置为0
            SharePreferenceUtil.putString(TOP_INFO_CACHE_DATA_KEY, currentDate);

            //处理终端布局后续逻辑
            SharePreferenceUtil.putString(cacheKey, json.encode(bean));
            if(bean != null && bean.data != null && bean.data.bindTerminalList != null){
              VgEventBus.global.send(new TerminalNumRefreshEvent(bean.data.bindTerminalList.length));
            }
            if(bindTermainalInfoValueNotifier?.value != null
                && bindTermainalInfoValueNotifier?.value?.data?.bindTerminalList != null
                && bindTermainalInfoValueNotifier.value.data.bindTerminalList.length>index){
              getTerminalDetail(bindTermainalInfoValueNotifier?.value?.data?.bindTerminalList[index]?.hsn);
            }
          },
          onError: (msg){
            VgEventBus.global.send(new HomePageInterfaceEventMonitor(showLoad: false));
            showLoad = false;
            VgToastUtils.toast(AppMain.context, msg);
          }
      ));
    }else{
      Future<String> latlng = VgLocationUtils.getCacheLatLngString();
      latlng.then((value){
        ///网络请求
        VgHttpUtils.get(NetApi.HOME_PUNCH_AND_TERMINAL_INFO,params: {
          "authId":requestAuthId,
          "gps": value,
        },callback: BaseCallback(
            onSuccess: (val){
              String currentAuthId = UserRepository.getInstance().authId;
              if(requestAuthId != currentAuthId){
                print("两次authId不一致，忽略此次请求");
                return;
              }
              IndexBindTermainalInfo bean = IndexBindTermainalInfo.fromMap(val);
              if(!isStateDisposed){
                bindTermainalInfoValueNotifier?.value = bean;
                indexTopPunchInfoValueNotifier?.value = bean.data.PVCnt;
              }
              //处理打卡布局后续逻辑
              VgEventBus.global.send(new HomePageInterfaceEventMonitor(showLoad: false));
              showLoad = false;
              //缓存获取打卡数据的日期，便于日期切换时将不是当前日期的缓存数据置为0
              SharePreferenceUtil.putString(TOP_INFO_CACHE_DATA_KEY, currentDate);

              //处理终端布局后续逻辑
              SharePreferenceUtil.putString(cacheKey, json.encode(bean));
              if(bean != null && bean.data != null && bean.data.bindTerminalList != null){
                VgEventBus.global.send(new TerminalNumRefreshEvent(bean.data.bindTerminalList.length));
              }
              VgEventBus.global.send(new HomePageInterfaceEventMonitor(showLoad: false));
              showLoad = false;
              if(bindTermainalInfoValueNotifier?.value != null
                  && bindTermainalInfoValueNotifier?.value?.data?.bindTerminalList != null
                  && bindTermainalInfoValueNotifier.value.data.bindTerminalList.length>index){
                getTerminalDetail(bindTermainalInfoValueNotifier?.value?.data?.bindTerminalList[index]?.hsn);
              }
            },
            onError: (msg){
              VgEventBus.global.send(new HomePageInterfaceEventMonitor(showLoad: false));
              showLoad = false;
              VgToastUtils.toast(AppMain.context, msg);
            }
        ));
      });
    }
  }

  //清空首页公司基础信息缓存
  void clearHomeBaseInfoCache(){
    indexTopBaseValueNotifier?.value = new IndexTopBaseInfo();
  }

  //清空首页打卡信息缓存
  void clearHomePunchInfoCache(){
    indexTopPunchInfoValueNotifier?.value = new PVCntBean();
    print("卡片：2222222");
  }

  //清空首页终端信息缓存
  void clearHomeTerInfo(){
    bindTermainalInfoValueNotifier?.value = new IndexBindTermainalInfo();
  }

  //清空终端以及打卡信息缓存
  void clearPunchAndTerminalInfo(){
    // punchAndTerminalInfoValueNotifier?.value = new IndexBindTermainalInfo();
  }

  //每次启动获取所有终端详情以及每个终端下的播放列表
  //一般只获取一次
  void getInitTerminalInfoAndPlayList({String gps, String authId}){
    String requestAuthId = StringUtils.isNotEmpty(authId)?authId:(UserRepository.getInstance().authId ?? "");
    print("初始化获取终端以及播放列表失败");
    if(StringUtils.isNotEmpty(gps)){
      VgHttpUtils.get(NetApi.HOME_PUNCH_AND_TERMINAL_INFO,params: {
        "authId":requestAuthId,
        "gps": gps,
      },callback: BaseCallback(
          onSuccess: (val){
            String currentAuthId = UserRepository.getInstance().authId;
            if(requestAuthId != currentAuthId){
              print("两次authId不一致，忽略此次请求");
              return;
            }
            IndexBindTermainalInfo bean = IndexBindTermainalInfo.fromMap(val);
            if(bean != null
                && bean.data != null
                && bean.data.bindTerminalList != null
                && bean.data.bindTerminalList.length > 0){
              bean.data.bindTerminalList.forEach((element) {
                getTerminalPlayListAndCache(element?.hsn);
              });
            }
          },
          onError: (msg){
            print("初始化获取终端以及播放列表失败：" + msg);
          }
      ));
    }else{
      Future<String> latlng = VgLocationUtils.getCacheLatLngString();
      latlng.then((value){
        ///网络请求
        VgHttpUtils.get(NetApi.HOME_PUNCH_AND_TERMINAL_INFO,params: {
          "authId":requestAuthId,
          "gps": value,
        },callback: BaseCallback(
            onSuccess: (val){
              String currentAuthId = UserRepository.getInstance().authId;
              if(requestAuthId != currentAuthId){
                print("两次authId不一致，忽略此次请求");
                return;
              }
              IndexBindTermainalInfo bean = IndexBindTermainalInfo.fromMap(val);
              if(bean != null
                  && bean.data != null
                  && bean.data.bindTerminalList != null
                  && bean.data.bindTerminalList.length > 0){
                bean.data.bindTerminalList.forEach((element) {
                  getTerminalPlayListAndCache(element?.hsn);
                });
              }
            },
            onError: (msg){
              print("初始化获取终端以及播放列表失败：" + msg);
            }
        ));
      });
    }
  }


  // bool showLoad = false;
  ///获取顶部信息请求
  // void getTopInfoHttp(int index, {bool blockUpdate, String unbindHsn, String gps}){
  //   if(StringUtils.isEmpty(UserRepository.getInstance().authId)){
  //     return;
  //   }
  //   // homePageInterfaceEventMonitor = VgEventBus.global.on<HomePageInterfaceEventMonitor>().listen((event) {
  //   //   showLoad = false;
  //   // });
  //   homePageInterfaceEventMonitor = VgEventBus.global.on<UpdateHomePageEventMonitor>().listen((event) {
  //     showLoad = true;
  //   });
  //   if(!showLoad && (blockUpdate??true)){
  //     VgEventBus.global.send(new HomePageInterfaceEventMonitor(showLoad: true));
  //     showLoad = true;
  //   }
  //   String currentDate = DateUtil.getDateStrByDateTime(DateTime.now(), format: DateFormat.YEAR_MONTH_DAY);
  //   print("currentDate:${currentDate}");
  //   String cacheKey = INDEX_TOP_INFO_API + (UserRepository.getInstance().authId??"")
  //       + (UserRepository.getInstance().companyId??"");
  //
  //   ///获取缓存数据
  //   Future<String> future = SharePreferenceUtil.getString(cacheKey);
  //   Future<String> topInfoCacheData = SharePreferenceUtil.getString(TOP_INFO_CACHE_DATA_KEY);
  //   future.then((jsonStr){
  //     if(!StringUtils.isEmpty(jsonStr)){
  //       Map map = json.decode(jsonStr);
  //       IndexTopInfoResponseBean bean = IndexTopInfoResponseBean.fromMap(map);
  //       if(bean != null){
  //         ///刷新后更新当前角色
  //         UserRepository.getInstance().updateCurrentRoleId(bean?.data?.roleid);
  //         if(!isStateDisposed){
  //           topInfoCacheData.then((cacheDate) {
  //             if(currentDate != cacheDate){
  //               bean?.data?.PVCnt?.historyPunchCnt = 0;
  //               bean?.data?.PVCnt?.punchcnt = 0;
  //               bean?.data?.PVCnt?.visitorcnt = 0;
  //             }
  //             topInfoValueNotifier?.value = bean?.data;
  //           });
  //         }
  //         print("111111:获取顶部信息缓存");
  //         if(bean?.data != null
  //             && bean?.data?.bindTerminalList != null
  //             && bean.data.bindTerminalList.length>index){
  //           if(StringUtils.isEmpty(unbindHsn) || (unbindHsn != bean?.data?.bindTerminalList[index]?.hsn)){
  //             getTerminalDetail(bean?.data?.bindTerminalList[index]?.hsn);
  //           }
  //         }
  //       }
  //       // VgEventBus.global.send(new HomePageInterfaceEventMonitor(showLoad: true));
  //       // showLoad = true;
  //     }
  //   });
  //   if(StringUtils.isNotEmpty(gps)){
  //     print("使用首页获取到的gps去执行请求");
  //     ///网络请求
  //     VgHttpUtils.get(INDEX_TOP_INFO_API,params: {
  //       "authId":UserRepository.getInstance().authId ?? "",
  //       "companyid": UserRepository.getInstance().companyId ?? "",
  //       "gps": gps,
  //     },callback: BaseCallback(
  //         onSuccess: (val){
  //           IndexTopInfoResponseBean bean = IndexTopInfoResponseBean.fromMap(val);
  //           ///刷新后更新当前角色
  //           if(bean!=null){
  //             UserRepository.getInstance().updateCurrentRoleId(bean?.data?.roleid);
  //             SharePreferenceUtil.putString(cacheKey, json.encode(bean));
  //             SharePreferenceUtil.putString(TOP_INFO_CACHE_DATA_KEY, currentDate);
  //             if(bean.data != null && bean.data.bindTerminalList != null){
  //               VgEventBus.global.send(new TerminalNumRefreshEvent(bean?.data?.bindTerminalList?.length));
  //             }else{
  //               VgEventBus.global.send(new TerminalNumRefreshEvent(0));
  //             }
  //
  //           }
  //           topInfoValueNotifier?.value = bean?.data;
  //           if(topInfoValueNotifier?.value != null
  //               && topInfoValueNotifier?.value?.bindTerminalList != null
  //               && topInfoValueNotifier.value.bindTerminalList.length>index){
  //             getTerminalDetail(topInfoValueNotifier?.value?.bindTerminalList[index]?.hsn);
  //           }
  //           VgEventBus.global.send(new HomePageInterfaceEventMonitor(showLoad: false));
  //           showLoad = false;
  //         },
  //         onError: (msg){
  //           VgEventBus.global.send(new HomePageInterfaceEventMonitor(showLoad: false));
  //           VgToastUtils.toast(AppMain.context, msg);
  //           showLoad = false;
  //         }
  //     ));
  //   }else{
  //     Future<String> latlng = VgLocationUtils.getCacheLatLngString();
  //     latlng.then((value){
  //       ///网络请求
  //       VgHttpUtils.get(INDEX_TOP_INFO_API,params: {
  //         "authId":UserRepository.getInstance().authId ?? "",
  //         "companyid": UserRepository.getInstance().companyId ?? "",
  //         "gps": value,
  //       },callback: BaseCallback(
  //           onSuccess: (val){
  //             IndexTopInfoResponseBean bean = IndexTopInfoResponseBean.fromMap(val);
  //             ///刷新后更新当前角色
  //             if(bean!=null){
  //               UserRepository.getInstance().updateCurrentRoleId(bean?.data?.roleid);
  //               SharePreferenceUtil.putString(cacheKey, json.encode(bean));
  //               SharePreferenceUtil.putString(TOP_INFO_CACHE_DATA_KEY, currentDate);
  //               if(bean.data != null && bean.data.bindTerminalList != null){
  //                 VgEventBus.global.send(new TerminalNumRefreshEvent(bean?.data?.bindTerminalList?.length));
  //               }else{
  //                 VgEventBus.global.send(new TerminalNumRefreshEvent(0));
  //               }
  //
  //             }
  //             topInfoValueNotifier?.value = bean?.data;
  //             if(topInfoValueNotifier?.value != null
  //                 && topInfoValueNotifier?.value?.bindTerminalList != null
  //                 && topInfoValueNotifier.value.bindTerminalList.length>index){
  //               getTerminalDetail(topInfoValueNotifier?.value?.bindTerminalList[index]?.hsn);
  //             }
  //             VgEventBus.global.send(new HomePageInterfaceEventMonitor(showLoad: false));
  //             showLoad = false;
  //           },
  //           onError: (msg){
  //             VgEventBus.global.send(new HomePageInterfaceEventMonitor(showLoad: false));
  //             VgToastUtils.toast(AppMain.context, msg);
  //             showLoad = false;
  //           }
  //       ));
  //     });
  //   }
  //
  //
  // }

  ///获取终端详情
  void getTerminalDetail(String hsn){
    if(StringUtils.isEmpty(UserRepository.getInstance().authId)){
      return;
    }
    String cacheKey = NetApi.TERMINAL_PLAY_LIST_API + (UserRepository.getInstance().getCacheKeySuffix()??"")
        + (hsn??"");
    print("cacheKey:" + cacheKey);
    ///获取缓存数据
    Future<String> future = SharePreferenceUtil.getString(cacheKey);
    future.then((jsonStr){
      if(!StringUtils.isEmpty(jsonStr)){
        Map map = json.decode(jsonStr);
        TerminalDetailResponseBean bean = TerminalDetailResponseBean.fromMap(map, isCache: true);
        if(bean != null){
          if(!isStateDisposed){
            detailValueNotifier?.value = bean;
          }
          print("111111:获取终端详情缓存");
        }
      }
    });

    ///网络请求
    VgHttpUtils.get(NetApi.TERMINAL_PLAY_LIST_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn": hsn ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          TerminalDetailResponseBean bean = TerminalDetailResponseBean.fromMap(val);
          if(!isStateDisposed){
            detailValueNotifier?.value = bean;
          }
          if(bean != null){
            SharePreferenceUtil.putString(cacheKey, json.encode(bean));
          }
          Future.delayed(Duration(milliseconds: 1000), (){
            getUpdateTerminalPlayListStatus(hsn);
          });
        },
        onError: (msg){
          if("服务器内部错误" != msg){
            VgToastUtils.toast(AppMain.context, msg);
          }
        }
    ));
  }


  ///从网络获取终端详情并仅缓存
  void getTerminalPlayListAndCache(String hsn){
    if(StringUtils.isEmpty(UserRepository.getInstance().authId)){
      return;
    }
    print("从网络获取终端详情并仅缓存：" + hsn);
    String cacheKey = NetApi.TERMINAL_PLAY_LIST_API + (UserRepository.getInstance().getCacheKeySuffix()??"")
        + (hsn??"");
    ///网络请求
    VgHttpUtils.get(NetApi.TERMINAL_PLAY_LIST_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn": hsn ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          TerminalDetailResponseBean bean = TerminalDetailResponseBean.fromMap(val);
          if(bean != null){
            SharePreferenceUtil.putString(cacheKey, json.encode(bean));
          }
        },
        onError: (msg){
          print("从网络获取终端详情并仅缓存失败：" + msg);
        }
    ));
  }

  ///获取是否有紧急通告
  void getUrgent(){
    String authId = UserRepository.getInstance().authId;
    if(StringUtils.isEmpty(authId)){
      return;
    }
    String cacheKey = GET_URGENT_API + (UserRepository.getInstance().authId??"");
    ///网络请求
    VgHttpUtils.get(GET_URGENT_API,params: {
      "authId":authId ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          MediaUrgentResponseBean bean = MediaUrgentResponseBean.fromMap(val);
          urgentValueNotifier?.value = bean;
          String urgentPicId = "";
          if(bean != null && bean.data != null && bean.data.list != null && bean.data.list.length > 0){
            if(StringUtils.isNotEmpty(bean.data.list[0]?.id)){
              urgentPicId = bean.data.list[0]?.id;
            }
          }
          SharePreferenceUtil.putString(cacheKey, urgentPicId);
        },
        onError: (msg){
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  ///重复播放/取消重复播放资源 picid暂停图片id，取消传空 stopflg01 暂停 02取消暂停
  void repeatPlay(BuildContext context,String picid, String stopflg, String id, String hsn, {VoidCallback callback}){
    if(StringUtils.isEmpty(picid)){
      return;
    }
//    VgHudUtils.show(context,"");
    VgHttpUtils.get(REPEAT_PLAY_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn":hsn,
      "picid": picid ?? "",
      "stopflg": stopflg ?? "",
      "id": id ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          if("02" == stopflg){
            OperationSuccessTipsDialog.navigatorPushDialog(context, title: "循环播放已关闭");
          }
          if(callback != null){
            callback.call();
          }
          Future.delayed(Duration(milliseconds: 1000), (){
            //通知首页更新
            VgEventBus.global.send(IndexRefreshEven(hsn: hsn));
            getUpdateTerminalPlayListStatus(hsn);
          });
        },
        onError: (msg){
          VgHudUtils.hide(context);

          VgToastUtils.toast(context, msg);
        }
    ));
  }

  ///重复播放/取消重复播放资源
  void repeatBuildingIndex(BuildContext context,String hsn, String buildingIndexId, String stopflg, {VoidCallback callback}){
    if(StringUtils.isEmpty(buildingIndexId)){
      return;
    }
//    VgHudUtils.show(context,"");
    VgHttpUtils.get(NetApi.REPEAT_BUILDING_INDEX,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn":hsn,
      "id": buildingIndexId ?? "",
      "stopflg": stopflg ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          if("00" == stopflg){
            OperationSuccessTipsDialog.navigatorPushDialog(context, title: "循环播放已关闭");
          }
          if(callback != null){
            callback.call();
          }
          Future.delayed(Duration(milliseconds: 1000), (){
            //通知首页更新
            VgEventBus.global.send(IndexRefreshEven(hsn: hsn));
            getUpdateTerminalPlayListStatus(hsn);
          });
        },
        onError: (msg){
          VgHudUtils.hide(context);

          VgToastUtils.toast(context, msg);
        }
    ));
  }

  ///重复播放/取消重复播放智能家居
  ///01重复播放 00取消重复
  void repeatSmartHome(BuildContext context,String hsn, String rasid, String stopflg, {VoidCallback callback}){
    if(StringUtils.isEmpty(rasid)){
      return;
    }
    VgHttpUtils.get(NetApi.REPEAT_SMART_HOME,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn":hsn,
      "rasid": rasid ?? "",
      "stopflg": stopflg ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          if("00" == stopflg){
            OperationSuccessTipsDialog.navigatorPushDialog(context, title: "循环播放已关闭");
          }
          if(callback != null){
            callback.call();
          }
          Future.delayed(Duration(milliseconds: 1000), (){
            //通知首页更新
            VgEventBus.global.send(IndexRefreshEven(hsn: hsn));
            getUpdateTerminalPlayListStatus(hsn);
          });
        },
        onError: (msg){
          VgHudUtils.hide(context);

          VgToastUtils.toast(context, msg);
        }
    ));
  }


  ///根据终端id取消重复播放
  void cancelRepeatPlayByHsn(BuildContext context, String hsn){
    VgHttpUtils.get(CANCEL_REPEAT_PLAY_BY_HSN_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn":hsn,
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          OperationSuccessTipsDialog.navigatorPushDialog(context, title: "循环播放已关闭");

          Future.delayed(Duration(milliseconds: 1000), (){
            //通知首页更新
            VgEventBus.global.send(IndexRefreshEven(hsn: hsn));
            getUpdateTerminalPlayListStatus(hsn);
          });
        },
        onError: (msg){
          VgHudUtils.hide(context);

          VgToastUtils.toast(context, msg);
        }
    ));
  }

  ///开关声音
  ///onOff 00开 01关
  void changeVolume(BuildContext context, String hsn, String onOff, int volume,
      int selectIndex) {
    if (StringUtils.isEmpty(hsn)) {
      return;
    }
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.get(CHANGE_VOLUME_API,
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "hsn": hsn ?? "",
          "onOff": onOff ?? "00",
          "volume": volume ?? 50,
        },
        callback: BaseCallback(onSuccess: (val) {
          BaseResponseBean bean =
          BaseResponseBean.fromMap(val);
          VgToastUtils.toast(AppMain.context, "操作成功");
          Future.delayed(Duration(milliseconds: 1000), (){
            //通知首页更新
            getHomeTerminalInfo(selectIndex);
            // getPunchAndTerminalInfo(selectIndex, hideShowLoad: false);
            // getTopInfoHttp(selectIndex, blockUpdate: false);
            getUpdateTerminalPlayListStatus(hsn);
          });
        }, onError: (msg) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);
        }));
  }

  ///查询终端获取资源是否成功
  void getUpdateTerminalPlayListStatus(String hsn){
    String authId = UserRepository.getInstance().authId;
    if(StringUtils.isEmpty(authId)){
      return;
    }
    ///网络请求
    VgHttpUtils.get(NetApi.UPDATE_TERMINAL_PLAY_LIST_STATUS_API,params: {
      "authId":authId ?? "",
      "hsn":hsn ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          UpdateTerminalPlayListStatusBean bean = UpdateTerminalPlayListStatusBean.fromMap(val);
          if(bean != null){
            VgEventBus.global.send(new UpdateTerminalPlayListStatusEvent(bean?.data?.obtainflg??"", hsn));
          }
        },
        onError: (msg){
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }
}